package com.example.ordermealservice.Api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.commonutils.R;
import com.example.ordermealservice.entity.OrderDish;
import com.example.ordermealservice.entity.vo.DishSelectByConditionApiVo;
import com.example.ordermealservice.service.OrderDishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/ordermealservice/orderdishApi")
public class OrderDishApi {
    @Autowired
    private OrderDishService orderDishService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //带条件的分页查询(根据菜品名称、菜品分类、排序方式等多条件进行查询)
    //仅展示库存大于0的菜品
    //仅展示出售中的菜品
    @PostMapping("/selectPageByCondition/{page}/{pageSize}")
//    @Cacheable(key = "'dishList'",value = "dish")
    //TODO 加上缓存后，分页跳转不了
    public R selectPageByCondition(@RequestBody DishSelectByConditionApiVo dishSelectByConditionApiVo,
                                   @PathVariable int page, @PathVariable int pageSize){

        String oldConditionJson = stringRedisTemplate.opsForValue().get("DishSelectByConditionApiVo");
        String newConditionJson = JSONUtil.toJsonStr(dishSelectByConditionApiVo);
        stringRedisTemplate.opsForValue().set("DishSelectByConditionApiVo",newConditionJson,30,TimeUnit.MINUTES);
        if (!newConditionJson.equals(oldConditionJson)){
            stringRedisTemplate.delete("cache:dishAmount");
        }
        //从缓存中获取总记录数
        String totalJson = stringRedisTemplate.opsForValue().get("cache:dishAmount");
        //从缓存中获取当前页的订单
        String dishesJson = stringRedisTemplate.opsForValue().get("cache:dishes:" + "page" + page + "pageSize" + pageSize);
        if (StrUtil.isNotBlank((totalJson)) && StrUtil.isNotBlank((dishesJson))){
            List<OrderDish> records = JSONUtil.toList(dishesJson, OrderDish.class);
            //由于是分页查询，返回的是Page类型，所以缓存的结果也封装成该类型
            Page<OrderDish> pageInfo = new Page<>(page,pageSize);
            pageInfo.setRecords(records);
            pageInfo.setTotal(Long.parseLong(totalJson));
            return R.ok().data("pageInfo",pageInfo);
        }
        LambdaQueryWrapper<OrderDish> queryWrapper = new LambdaQueryWrapper<>();
        String dishName = dishSelectByConditionApiVo.getDishName();
        String category = dishSelectByConditionApiVo.getCategory();
        String subCategory = dishSelectByConditionApiVo.getSubCategory();
        Integer sort = dishSelectByConditionApiVo.getSort();
        queryWrapper.like(null != dishName,OrderDish::getDishName,dishName);
        queryWrapper.eq(null != category,OrderDish::getDishClassification,category);
        queryWrapper.eq(null != subCategory,OrderDish::getDishSubclassification,subCategory);
        queryWrapper.gt(OrderDish::getDishNumber,0);
        queryWrapper.eq(OrderDish::getDishStatus,1);
        if (null != sort){
            switch (sort){
                case 1:queryWrapper.orderByDesc(OrderDish::getDishTime);
                case 2:queryWrapper.orderByAsc(OrderDish::getDishTime);
                case 3:queryWrapper.orderByDesc(OrderDish::getDishPrice);
                case 4:queryWrapper.orderByAsc(OrderDish::getDishPrice);
            }
        }
        queryWrapper.orderByDesc(OrderDish::getGmtCreate);
        Page<OrderDish> pageInfo = new Page<>(page,pageSize);
        orderDishService.page(pageInfo,queryWrapper);
        //总记录数存入缓存
        long total = pageInfo.getTotal();
        stringRedisTemplate.opsForValue().set("cache:dishAmount", total+"",30, TimeUnit.MINUTES);
        //每一页的数据存入缓存
        List<OrderDish> records = pageInfo.getRecords();
        stringRedisTemplate.opsForValue().set("cache:dishes:" + "page" + page + "pageSize" + pageSize,
                JSONUtil.toJsonStr(records),30, TimeUnit.MINUTES);
        return R.ok().data("pageInfo",pageInfo);
    }
}
